package com.cym.controller.adminPage;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.cym.model.Www;
import com.cym.model.dto.ZipCheckDTO;
import com.cym.service.WwwService;
import com.cym.sqlhelper.bean.Page;
import com.cym.sqlhelper.bean.Sort;
import com.cym.sqlhelper.bean.Sort.Direction;
import com.cym.utils.BaseController;
import com.cym.utils.JsonResult;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.ModelAndView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;

@Mapping("/adminPage/www")
@Controller
public class WwwController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(WwwController.class);
    @Inject
    WwwService wwwService;

    @Mapping
    public ModelAndView index(ModelAndView modelAndView) {

        modelAndView.put("list", sqlHelper.findAll(new Sort("dir", Direction.ASC), Www.class));
        modelAndView.view("/adminPage/www/index.html");
        return modelAndView;
    }

    /**
     * 备份分页查询
     */
    @Mapping("bak")
    public ModelAndView bakIndex(ModelAndView modelAndView, Page page) {
        modelAndView.put("page", wwwService.search(page));
        modelAndView.view("/adminPage/www/bak.html");
        return modelAndView;
    }

    /**
     * 备份分页查询
     */
    @Mapping("bak/restore")
    public JsonResult bakIndex(String id) {
        wwwService.restore(id);
        return renderSuccess();
    }

    /**
     * 添加/更新静态资源包
     *
     * @param www     静态包信息
     * @param zipTemp 压缩包临时路径
     * @return /
     */
    @Mapping("addOver")
    public JsonResult addOver(Www www, String zipTemp) {
        String time = System.nanoTime() + "";
        String tempDir = FileUtil.getTmpDirPath() + "/" + time;
        try {
            String zipName = zipTemp.substring(zipTemp.lastIndexOf("/") + 1);
            // 检查压缩包文件
            ZipCheckDTO checkDTO = wwwService.check(www, zipName, zipTemp, tempDir, time);
            if (!checkDTO.getPass()) {
                return renderError(checkDTO.getErrorMsg());
            }
            // 备份
            wwwService.backup(www.getId());

            ZipUtil.unzip(zipTemp, www.getDir());
            www.setIndexDir(www.getDir() + checkDTO.getRootPath());
            www.setZipName(zipName);
            sqlHelper.insertOrUpdate(www);

            return renderSuccess();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            FileUtil.del(zipTemp);
            FileUtil.del(tempDir);
        }

        return renderError(m.get("wwwStr.zipError"));
    }

    @Mapping("updateName")
    public JsonResult updateName(Www www) {
        if (sqlHelper.findById(www.getId(), Www.class) != null) {
            Www w = new Www();
            w.setId(www.getId());
            w.setName(www.getName());
            sqlHelper.updateById(w);
        }
        return renderSuccess();
    }

    @Mapping("del")
    public JsonResult del(String id) {
        sqlHelper.deleteById(id, Www.class);

        return renderSuccess();
    }

    @Mapping("detail")
    public JsonResult detail(String id) {
        Www www = sqlHelper.findById(id, Www.class);

        return renderSuccess(www);
    }

    public String getClassPath() throws Exception {
        try {
            String strClassName = getClass().getName();
            String strPackageName = "";
            if (getClass().getPackage() != null) {
                strPackageName = getClass().getPackage().getName();
            }
            String strClassFileName = "";
            if (!"".equals(strPackageName)) {
                strClassFileName = strClassName.substring(strPackageName.length() + 1, strClassName.length());
            } else {
                strClassFileName = strClassName;
            }
            URL url = null;
            url = getClass().getResource(strClassFileName + ".class");
            String strURL = url.toString();
            strURL = strURL.substring(strURL.indexOf('/') + 1, strURL.lastIndexOf('/'));
            // 返回当前类的路径，并且处理路径中的空格，因为在路径中出现的空格如果不处理的话，
            // 在访问时就会从空格处断开，那么也就取不到完整的信息了，这个问题在web开发中尤其要注意
            return strURL.replaceAll("%20", " ");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }
}
